package com.bytedance.frameworks.baselib.network.dispatcher;

import android.support.design.a;
import java.util.concurrent.atomic.AtomicBoolean;

public abstract class AbsRequest implements IRequest, Comparable, Runnable {
    protected final AtomicBoolean mCanceled;
    private final String mName;
    protected final Priority mPriority;
    private int mSequence;
    protected final AtomicBoolean mStarted;
    private static RequestQueue sRequestQueue = RequestQueue.getInstance();

    public AbsRequest(String name, Priority priority) {
        this.mStarted = new AtomicBoolean(false);
        this.mCanceled = new AtomicBoolean(false);
        this.mPriority = priority;
        if(a.isTextEmpty(name)) {
            name = this.getClass().getSimpleName();
        }

        this.mName = name;
    }

    public void cancel() {
        this.mCanceled.compareAndSet(false, true);
    }

    public int compareTo(IRequest request) {
        Priority thisPriority = this.getPriority();
        Priority thatPriority = request.getPriority();
        if(thisPriority == null) {
            thisPriority = Priority.NORMAL;
        }

        if(thatPriority == null) {
            thatPriority = Priority.NORMAL;
        }

        return thisPriority == thatPriority ? this.getSequence() - request.getSequence() : thatPriority.ordinal() - thisPriority.ordinal();
    }

    public int compareTo(Object arg2) {
        return this.compareTo(((IRequest)arg2));
    }

    public String getName() {
        return this.mName;
    }

    public Priority getPriority() {
        return this.mPriority;
    }

    public int getSequence() {
        return this.mSequence;
    }

    public boolean isCanceled() {
        return this.mCanceled.get();
    }

    public boolean isDownload() {
        return false;
    }

    public boolean needTryLocal() {
        return false;
    }

    public void run() {
    }

    public boolean run4Local() {
        return false;
    }

    public static void setRequestQueue(RequestQueue arg0) {
        AbsRequest.sRequestQueue = arg0;
    }

    public final AbsRequest setSequence(int arg1) {
        this.mSequence = arg1;
        return this;
    }

    public final void start() {
        if(this.mStarted.compareAndSet(false, true)) {
            if(AbsRequest.sRequestQueue == null) {
                AbsRequest.sRequestQueue = RequestQueue.getInstance();
            }

            if(this.isDownload()) {
                AbsRequest.sRequestQueue.downloadRequestEnqueue(this);
                return;
            }

            AbsRequest.sRequestQueue.apiRequestEnqueue(this);
        }
    }
}

